package com.amigo.online.provider.adv.quartz.job;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.StringRedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;

import com.amigo.online.common.param.adv.bo.AdvHomeInitBO;
import com.amigo.online.common.param.common.KeyValueModel;
import com.amigo.online.provider.adv.common.ConstantValue;
import com.amigo.online.provider.adv.service.AdvHomeApplyService;
import com.amigo.online.provider.adv.service.AdvHomeStockService;
import com.amigo.online.provider.adv.util.AdvBasicUtil;

/**
 * 结算已经结束的探探广告内容
 *
 * @author Administrator
 */

@Component
@EnableScheduling
public class SettleHomeAdvStockJob extends AbstractSettleAdvStockJob implements Job {

    @Autowired
    AdvHomeApplyService advHomeApplyService;

    @Autowired
    AdvHomeStockService advHomeStockService;

    @SuppressWarnings("unchecked")
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        logger.info("--结算首页--");
        long today = AdvBasicUtil.getTodayZeroPointTimeStamps();
        List<AdvHomeInitBO> settlePlanList = advHomeApplyService.listFindTomorrowAdvSettlePlanByEndTime(today);
        Map<String, Set<String>> initListMap = new HashMap<>(settlePlanList.size() * ConstantValue.ADV_AREA_SIZE);
        List<Long> setttleList = new LinkedList<>();
        for (AdvHomeInitBO temp : settlePlanList) {
            // 广告资源队列缓存入库，广告资源库存入库
            List<Integer> sexList = new ArrayList<>();
            int sexType = temp.getSexType();
            if (sexType == 0) {
                sexList.add(1);
                sexList.add(2);
            } else {
                sexList.add(sexType);
            }
            List<Integer> ageList = new ArrayList<>();
            int ageType = temp.getAgeType();
            AdvBasicUtil.tansferAgeTypeToList(ageType, ageList);
            // 地区，性别，年龄三个维度组合做投放队列
            for (Integer sex : sexList) {
                for (Integer age : ageList) {
                    int sexValue = sex;
                    int ageValue = age;
                    if (sex == 0 || age == 0) {
                        sexValue = ageValue = 0;
                    }
                    if (temp.getAreaType() == 2) {
                        for (Integer areaId : temp.getAreaList()) {
                            complexRedisInitMap(ConstantValue.ADV_HOME_LIST, areaId, sexValue, ageValue, initListMap,
                                    temp.getId());
                        }
                    } else if (temp.getAreaType() == 1) {
                        // 全国
                        complexRedisInitMap(ConstantValue.ADV_HOME_LIST, 0, sexValue, ageValue, initListMap, temp.getId());
                    } else if (temp.getAreaType() == 3) {
                        // mongo
                    }
                }
            }
            setttleList.add(temp.getId());
        }

        // 队列清除结算的广告
        // 管道操作，减少网络交互
        @SuppressWarnings("unused")
        List<Object> results = stringRedisTemplate.executePipelined(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                StringRedisConnection redisConn = (StringRedisConnection) connection;
                for (String key : initListMap.keySet()) {
                    for (String temp : initListMap.get(key)) {
                        redisConn.lRem(key, 1, temp);
                    }
                    redisConn.hDel(ConstantValue.ADV_HOME_TYPE_MAP, key);
                }
                return null;
            }
        });
        // 库存结算入库
        List<Integer> restNumber = redisTemplate.opsForHash().multiGet(ConstantValue.ADV_HOME_STOCK, setttleList);
        if (restNumber.contains(null)) {
            logger.error("缓存数据存在问题!");
        }
        List<KeyValueModel<Long, Integer>> updateObjectList = new LinkedList<>();
        for (int i = 0; i < settlePlanList.size(); i++) {
            if (restNumber.get(i) != null) {
                KeyValueModel<Long, Integer> tempModel = new KeyValueModel<Long, Integer>();
                tempModel.setId(settlePlanList.get(i).getId());
                tempModel.setValue(restNumber.get(i));
                updateObjectList.add(tempModel);
            } else {
                logger.error("结算首页广告库存存在问题，有问题ID:" + settlePlanList.get(i).getId());
            }
        }
        advHomeStockService.storageAdvRestNumberFromRedis(updateObjectList);
    }

}
